package org.tuestudent.grouppa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;

import org.tuestudent.grouppa.WallViewController.AddCommentResponse;
import org.tuestudent.grouppa.WallViewController.AddTopicResponse;
import org.tuestudent.grouppa.WallViewController.ChangeTopicResponse;
import org.tuestudent.grouppa.WallViewController.GetAllTopicsResponse;

import android.R.color;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.NotificationManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class Wall extends Fragment implements OnClickListener {

    // Container of all wall Items
    TableLayout wallItemList;
    // Row of the wallItemList
    TableRow wallItem;
    // GrouppaScreen
    GrouppaScreen grouppaScreen;

//  Array of String arrays
    String[][] responseArray; 
    
//  Title from the createTopicPopup  
    String topicTitle;
//  Comment from the createTopicPopup
    String topicComment;
    
    String user;
    
    Date currentDate;
    
    TextView contentTitle;
    TextView contentResponses;
    TextView contentPinned;
    Typeface tf;
    
    private static Wall instance=null;
    public static Wall getInstance()
    {
        return instance;
    }

    /**
     * method that opens the topic with id topicID
     * 
     * @param topicID
     *            the id of the topic
     */
    private void viewTopic(int topicID,ForumTopic topic) {
        getActivity().getFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, new ViewTopic(topicID,topic), "viewTopic")
        .addToBackStack(null)
        .commit();
    }

    /**
     * opens a popup with an editable text area containing the current info
     * 
     * This functionality is not yet implemented
     */
    private void editTopicPopup() {
        // TODO:create popup
        // TODO:create editable textfield
        // TODO:load the current groupinfo in the editable textfield
        // TODO:create close button
        // TODO:create confirm button
    }

    /**
     * updates the topic info
     * 
     * @param topicID
     *            the id of the topic of which the info should be updated
     * @param info
     *            the String containing the updated topic info
     * @modifies topicInfo
     */
    private void editTopicInfo(int topicID, String topicInfo) {
        topicInfoUpdated();
    }

    /**
     * popup to confirm that the topic info has successfully been updated
     * 
     * This functionality is not yet implemented
     */
    private void topicInfoUpdated() {
        // TODO:create popup to confirm that the topic info has successfully
        // been updated
        // TODO:create 'ok' confirmation button
    }

    /**
     * removes the topic with topic id topicID
     * 
     * @param topicID
     *            the id of the to be removed topic
     */
    private void removeTopic(int topicID) {
        // TODO:create code to remove topic with id topicID
    }

    /**
     * creates a popup to create a new topic
     */
    private void createTopicPopup() {
      //make the popup visible
        final AlertDialog createTopicPopup = grouppaScreen.showPopUp(R.layout.popup_create_topic);
        //add a listener to the button of the popup so it can do something when pressed on
        final Button createTopic = (Button)createTopicPopup.findViewById(R.id.createPostSend);
        
        createTopic.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {

                topicTitle = ((EditText) createTopicPopup.findViewById(R.id.createPostTitle)).getText().toString();

                topicComment = ((EditText) createTopicPopup.findViewById(R.id.createPostText)).getText().toString();
                
                // Validation of a topic title
                boolean check = true;
                if ( topicTitle.trim().isEmpty() ) {
                    check = false;
                    ((EditText) createTopicPopup.findViewById(R.id.createPostTitle))
                        .setError("Enter a topic title.");
                }
                // Validation of a topic comment
                else if ( topicComment.trim().isEmpty() ) {
                    check = false;
                    ((EditText) createTopicPopup.findViewById(R.id.createPostText))
                        .setError("Describe the topic.");
                }
                
                if (check) {
                    user = Main.getContext().currentUserName;
                    currentDate = new Date();
                    createTopicPopup.dismiss();
                    createTopic(topicTitle, topicComment, user, currentDate);
                }
            }
        });
        
        ImageButton cancel = (ImageButton)createTopicPopup.findViewById(R.id.createPostCancel);
        cancel.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                createTopicPopup.dismiss();
            }
        });
    }

    /**
     * create the topic with the filled in credentials
     * 
     * @param topicTitle
     *            the identifyer of the topic, this should be unique
     * @param postText
     *            the content of the topic
     * @param username
     *            the (nick)name of the user who created the topic
     * @param date
     *            the date of the creation of the topic
     * @param time
     *            the time of the creation of the topic
     */
    private void createTopic(String topicTitle, String postText, String username,
            Date cDate) {
        
        ForumTopic nTopic = new ForumTopic();
        nTopic.author = username;
        nTopic.title = topicTitle;
        nTopic.text = postText;
        nTopic.date = cDate;
        nTopic.isPinned = false;
        
//      Send the topic to the server.
        WallViewController.getInstance().addTopic(nTopic);
        
        grouppaScreen.busyMessage("creating topic...");
    }

    /**
     * popup to confirm that the topic has been succesfully created
     * 
     * @param topicID
     */
    private void topicCreatedPopup() {
        grouppaScreen.actionSuccess("The topic has been created");
    }

    private String[] getWallItems() {
        // temporary array with data for the wall
        String[] wallContent =
                { "This is the first topic", "26-03-2014", "10" };

        return wallContent;
    }

    // When the Fragment is attached to the activity
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.grouppaScreen = (GrouppaScreen) activity;
    }

    
    
 // ----------------onCreateView for the Wall Fragment-------------------

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // Inflate the view to its container
        View wall = inflater.inflate(R.layout.fragment_wall, container, false);

        wallItemList = (TableLayout) wall.findViewById(R.id.wall_list); 
        
//      set an onClickListener to the add post button
        Button addPost = (Button) wall.findViewById(R.id.add_post);
        addPost.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                createTopicPopup();
            }
        });

        //onclicklistener for changing the pinned state of topics
        pinnedStateSwitcher = new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                ForumTopic topic = currentTopics.get(v.getTag());
                ForumTopic newTopic = topic.clone();
                newTopic.isPinned = !topic.isPinned;
                WallViewController.getInstance().changeTopic(newTopic);
            }
        };
        
//      Typeface for wingdings
        tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/WINGDNG2.TTF"); 
        return wall;
    }

    OnClickListener pinnedStateSwitcher;
    // By clicking the element the view will change to the topic
    @Override
    public void onClick(View v) {
        TextView textView;
        // Textview to be declared by the topic
        if(v instanceof TableRow)
        {
            v.setBackgroundResource(color.holo_blue_light);
            textView = (TextView) ((TableRow)v).getChildAt(0);
        }
        else if(v instanceof TextView)
        {
            textView = (TextView)v;
            ((TableRow)textView.getParent()).setBackgroundResource(color.holo_blue_light);
        }
        else
            return;
        // Set the string to the topic selected by the user
        int topicId = (Integer)textView.getTag();
        if(topicId != -1)
        {
            viewTopic(topicId,currentTopics.get(topicId));
        }
    }

    // Method executed when the wall fragment is started
    @Override
    public void onStart() {
        super.onStart();
        AppContext ctx = Main.getContext();
        ctx.currentGrouppaFragment = this;
        WallViewController wvc = WallViewController.getInstance();
        ctx.setCurrentViewController(wvc);
        wvc.getAllTopics();
        //clearing forum notifications
        NotificationManager mNotificationManager =
            (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(ViewController.notificationIds.forumMessageNotification.ordinal());
    }

    // Dimensions for the elements on the wall
    int titleColWidth = 300;
    int responseColWidth = 75;
    int pinnedColWidth = 25;
    float titleColWeight = 0.675f;
    float responseColWeight = 0.25f;
    float pinnedColWeight = 0.125f;
    int contentSize = 25;
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
    HashMap<Integer,ForumTopic> currentTopics = new HashMap<Integer,ForumTopic>();
    
    /**
     * Response from server after request for all topics
     * 
     * @param response
     */
    public void onGetAllTopicsResponse(GetAllTopicsResponse response)
    {
        currentTopics.clear();
        ForumTopic[] allTopics = response.topics;
        
        ArrayList<ForumTopic> pinnedTopics = new ArrayList<ForumTopic>();
        ArrayList<ForumTopic> otherTopics  = new ArrayList<ForumTopic>();
        for (int i = 0; i < allTopics.length; i++ ) {
//          Select for every topic the data.p
            ForumTopic topic = allTopics[i];
            currentTopics.put(topic.id, topic);
            if(topic.isPinned)
                pinnedTopics.add(topic);
            else
                otherTopics.add(topic);             
        }  
        reloadTopics(pinnedTopics, otherTopics);
    }

    /**
     * Method dynamically creating the topics on the wall
     * 
     * @param pinnedTopics
     * @param otherTopics
     */
    private void reloadTopics(ArrayList<ForumTopic> pinnedTopics,
            ArrayList<ForumTopic> otherTopics) {
        wallItemList.removeAllViews();
        wallItem = new TableRow(getActivity());
        

        TextView content = new TextView(getActivity());
        content.setTag(-1);
//      Temporary text size
        content.setTextSize(30);
        content.setText("Title");
        content.setLayoutParams(lp);
        content.setLayoutParams(new TableRow.LayoutParams(titleColWidth, TableRow.LayoutParams.WRAP_CONTENT, titleColWeight));
        wallItem.addView(content);
        TextView content2 = new TextView(getActivity());
        content2.setTag(-1);
//      Temporary text size
        content2.setTextSize(30);
        content2.setText("Amount of\nresponses");
        content2.setLayoutParams(new TableRow.LayoutParams(responseColWidth, TableRow.LayoutParams.WRAP_CONTENT, responseColWeight));
        wallItem.addView(content2);
        TextView content3 = new TextView(getActivity());
        content3.setTag(-1);
//      Temporary text size
        
        content3.setTextSize(30);
        content3.setText("");
        content3.setLayoutParams(new TableRow.LayoutParams(pinnedColWidth, TableRow.LayoutParams.WRAP_CONTENT, pinnedColWeight));
        wallItem.addView(content3);
        
        wallItemList.addView(wallItem);
        
//      Sorts the ArrayList with topics on the date of creation
        Collections.sort(pinnedTopics, new Comparator<ForumTopic>() {

            @Override
            public int compare(ForumTopic p, ForumTopic q) {
                if (p.date.compareTo(q.date) > 0 )
                    return 1;
                else if (p.date.compareTo(q.date) < 0)
                    return -1;
                else
                    return 0;
            }
        });
        
        for(ForumTopic topic: pinnedTopics)
        {
//            print the sorted array
//            System.err.println(topic.date.toString());
            addTopicToList(topic); 
        }
        
//      Sorts the ArrayList on the date
        Collections.sort(otherTopics, new Comparator<ForumTopic>() {

            @Override
            public int compare(ForumTopic p, ForumTopic q) {
                if (p.date.compareTo(q.date) > 0 )
                    return 1;
                else if (p.date.compareTo(q.date) < 0)
                    return -1;
                else
                    return 0;
            }
        });
        
        for(ForumTopic topic: otherTopics)
        {
//            print the sorted array
//            System.err.println(topic.date.toString());
            addTopicToList(topic); 
        }
        wallItem.setLayoutParams(lp);
        wallItemList.requestLayout();
    }


    private void addTopicToList(ForumTopic topic) {
   
        wallItem = new TableRow(getActivity());
//        wallItem.setLayoutParams(lp);

        contentTitle = (TextView) View.inflate(getActivity(), 
                R.layout.wall_topic_title_textview, null);
        contentTitle.setTag(topic.id);
//          Temporary text size
        contentTitle.setTextSize(contentSize);
        contentTitle.setText(topic.title);
        contentTitle.setLayoutParams(lp);
        contentTitle.setLayoutParams(new TableRow.LayoutParams(titleColWidth, 
                TableRow.LayoutParams.WRAP_CONTENT, titleColWeight));
        contentTitle.setOnClickListener(this);
        wallItem.addView(contentTitle);
        contentResponses = (TextView) View.inflate(getActivity(), 
                R.layout.wall_topic_responses_amount_textview, null);
        contentResponses.setTag(topic.id);
//          Temporary text size
        contentResponses.setTextSize(contentSize);
        contentResponses.setText(String.valueOf(topic.responsesAmount));
        contentResponses.setLayoutParams(new TableRow.LayoutParams(responseColWidth, 
                TableRow.LayoutParams.WRAP_CONTENT, responseColWeight));
        contentResponses.setOnClickListener(this);
        wallItem.addView(contentResponses);
        contentPinned = (TextView) View.inflate(getActivity(), 
                R.layout.wall_topic_pinned_textview, null);
        contentPinned.setTag(topic.id);
//          Temporary text size
        contentPinned.setTextSize(contentSize);
        
        
//        if it is pinned then it needs a star: char 236 in wingdings.
        if(topic.isPinned)
            contentPinned.setBackgroundResource(R.drawable.star);
        contentPinned.setText("");
        
        
        contentPinned.setLayoutParams(new TableRow.LayoutParams(pinnedColWidth, 45, pinnedColWeight));
        contentPinned.setOnClickListener(pinnedStateSwitcher);
        wallItem.addView(contentPinned);
        wallItem.setOnClickListener(this);
        wallItem.setTag(topic.id);
        
        wallItem.setLayoutParams(lp);
        wallItemList.addView(wallItem);
        //contentPinned.requestLayout();
    }


    /**
     * Response from server after request to add a topic
     * 
     * @param response
     */
    public void onAddTopicResponse(AddTopicResponse response) {
        if(!response.succeeded)
        {
            grouppaScreen.errorPopup("failed to add a topic :"+response.errorReason);
            return;
        }
        ForumTopic topic = response.addedTopic;
        addTopicToList(topic);
        currentTopics.put(topic.id, topic);
        wallItemList.requestLayout();
        grouppaScreen.actionSuccess("topic was added!");
    }

    /**
     * Method executed when the topics are retrieved from the server
     * 
     * @param response
     */
    public void onGetChangedTopicsResponse(GetAllTopicsResponse response) {

        ForumTopic[] allTopics = response.topics;
        if(allTopics.length == 0)
            return;
        
        ArrayList<ForumTopic> pinnedTopics = new ArrayList<ForumTopic>();
        ArrayList<ForumTopic> otherTopics  = new ArrayList<ForumTopic>();
        for (int i = 0; i < allTopics.length; i++ ) {
//          Select for every topic the data
            ForumTopic topic = allTopics[i];
            currentTopics.put(topic.id, topic);
              
        }

        //Sorting the pinned and unpinned topic
        for(ForumTopic topic : currentTopics.values())
        {
            if(topic.isPinned)
                pinnedTopics.add(topic);
            else
                otherTopics.add(topic);
            
        }
       
        reloadTopics(pinnedTopics, otherTopics);
    }

    /**
     * Method executed when a topic is changed on the wall
     * 
     * @param response
     */
    public void onChangeTopicResponse(ChangeTopicResponse response) {
        if(!response.succeeded)
        {
            grouppaScreen.errorPopup("failed to change a topic :"+response.errorReason);
            return;
        }
        ForumTopic topic = response.changedTopic;
        currentTopics.put(topic.id, topic);


        ArrayList<ForumTopic> pinnedTopics = new ArrayList<ForumTopic>();
        ArrayList<ForumTopic> otherTopics  = new ArrayList<ForumTopic>();
        for(ForumTopic topic2 : currentTopics.values())
        {
            if(topic2.isPinned)
                pinnedTopics.add(topic2);
            else
                otherTopics.add(topic2);
            
        }
       
        reloadTopics(pinnedTopics, otherTopics);
        grouppaScreen.actionSuccess("topic was changed!");
        
    }

}
